﻿using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using doufu.Common;
using doufu.Model;

namespace doufu.Service
{
    public class UserIdentity : IIdentity, IPrincipal, IUserIdentity
    {

        public int UserId { get; set; }
        public string FullName { get; set; }
        public List<permission> UserPermission { get; set; }
        public const string cacheUserPermissionKey = "cache_user_permission";
        public const string cacheUserKey = "cache_user_info";

        public UserIdentity(IIdentity id)
        {
            //UserPermission = Caches.Read<List<permission>>(cacheUserPermissionKey);
            //if(UserPermission==null)
            //{
            //    UserPermission = UserDac.Instance.List("select p.* from permission p inner join user_permission up on p.permission_id=up.permission_id where up.user_id=@0", id.Name);
            //    Caches.Add(cacheUserPermissionKey)
            //}

            var user = Caches.Read<UserIdentity>(string.Format("{0}_{1}", cacheUserKey, id.Name));
            if (user == null)
            {
                UserPermission = CommonDac.Query(db => db.Fetch<permission>("select p.* from permission p inner join user_permission up on p.permission_id=up.permission_id where up.user_id=@0", id.Name));
                var u = CommonDac.Query(db => db.SingleOrDefault<users>("where user_id=@id", new { id = id.Name }));
                if (u != null)
                {
                    FullName = u.fullname;
                    UserId = u.user_id;
                }
                Caches.Add(string.Format("{0}_{1}", cacheUserKey, id.Name), this);
            }
            else
            {
                UserPermission = user.UserPermission;
                FullName = user.FullName;
                UserId = user.UserId;
            }
        }

        #region IIdentity 成员

        public string AuthenticationType
        {
            get { return "users"; }
        }

        public bool IsAuthenticated
        {
            get { return true; }
        }

        public string Name { get; set; }

        #endregion

        #region IPrincipal 成员

        public IIdentity Identity
        {
            get { return this; }
        }

        public bool IsInRole(string role)
        {
            return UserPermission.Count(x => x.permission_code == role) > 0;
        }

        public bool IsInRole(string controller, string action)
        {
            return UserPermission.Count(x => x.permission_code.TrimEnd('/').ToLower() == string.Format("/{0}/{1}", controller.ToLower(), action.ToLower())) > 0;
        }

        #endregion
    }
}